#include"Heap.h"

void HPInit(HP* php)
{
	assert(php);
	php->a = NULL;
	php->capacity = php->size = 0;
}
void HPDestroy(HP* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = php->size = 0;
}

void Swap(HPDataTypef* child, HPDataTypef* parent)
{
	HPDataTypef tmp = *child;
	*child = *parent;
	*parent = tmp;
}

void AdjustUp(HPDataTypef*a,int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HPPush(HP* php, HPDataTypef x)
{
	if (php->capacity == php->size)
	{
		int newcapacity = php->capacity == 0 ? 4 : 2 * php->capacity;
		HPDataTypef* tmp = (HPDataTypef*)realloc(php->a, sizeof(HPDataTypef) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc");
			return 0;
		}
		php->a = tmp;
		php->capacity = newcapacity;
	}
	assert(php->a);
	//php->a[2] = 1;
	php->a[php->size] = x;
	php->size++;

	AdjustUp(php->a, php->size - 1);
}
void AdjustDown(HPDataTypef* a,int n,int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child] < a[child + 1])
			child++;
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
		}
		parent = child;
		child = parent * 2 + 1;
	}
}

void HPPop(HP* php)
{
	assert(php);
	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;

	AdjustDown(php->a, php->size, 0);
}

HPDataTypef HPTop(HP* php)
{
	assert(php);
	assert(php->size);

	return php->a[0];
}
bool HPEmpty(HP* php)
{
	assert(php);

	return php->size == 0;
}

